from PIL import Image
import os

# ==================图片集分类的方法===========================
def getSpecifiedTypeFileFromDirectory(file_dir, suffixes):
    """
    获取路径下所有具某些指定后缀的文件
    :param file_dir: 根路径
    :param suffixes: 后缀集合
    :return:
    """
    L = []
    for dirpath, dirnames, filenames in os.walk(file_dir):
        for file in filenames:
            if file[0] == ".":
                continue
            if os.path.splitext(file)[1] in suffixes:
                currentPath = os.path.join(dirpath, file)
                L.append(currentPath)
    return L

def getFileNameFromDir(file_dir,suffixes):
    """
    从目录获取指定文件的文件名包含后缀
    :param file_dir: 路径
    :param suffixes: 指定后缀
    :return:
    """
    L = []
    for dirpath, dirnames, filenames in os.walk(file_dir):
        for file in filenames:
            if file[0] == ".":
                continue
            if os.path.splitext(file)[1] in suffixes:
                L.append(file)
    return L

def getFileNameNotSufFromDir(file_dir,suffixes):
    """
    从指定路径中获取特定后缀的文件名不包含后缀
    :param file_dir:
    :param suffixes:
    :return:
    """
    L = []
    for dirpath, dirnames, filenames in os.walk(file_dir):
        for file in filenames:
            if file[0] == ".":
                continue
            files = os.path.splitext(file)
            if files[1] in suffixes:
                L.append(files[0])
    return L

def getFileNameNotSufFromList(pathList):
    """
    从路径集合中获取文件名集合不包含后缀
    :param pathList:
    :param suffixes:
    :return:
    """
    L = []
    for item in pathList:
        basename = os.path.basename(item)
        L.append(os.path.splitext(basename)[0])
    return L

def getFileNameNotSufFromPath(path):
    """
    从路径中获取文件名，不包含后缀
    :param path:
    :return:
    """
    basename = os.path.basename(path)
    return os.path.splitext(basename)[0]
# ==================图片去黑边的工具方法========================

def isCrust(pix):
    return sum(pix) < 25


def hCheck(img, y, step=50):
    count = 0
    width = img.size[0]
    for x in range(0, width, step):
        if isCrust(img.getpixel((x, y))):
            count += 1
        if count > width / step / 2:
            return True
    return False


def vCheck(img, x, step=50):
    count = 0
    height = img.size[1]
    for y in range(0, height, step):
        if isCrust(img.getpixel((x, y))):
            count += 1
        if count > height / step / 2:
            return True
    return False


def boundaryFinder(img, crust_side, core_side, checker):
    if not checker(img, crust_side):
        return crust_side
    if checker(img, core_side):
        return core_side

    mid = (crust_side + core_side) / 2
    while mid != core_side and mid != crust_side:
        if checker(img, mid):
            crust_side = mid
        else:
            core_side = mid
        mid = (crust_side + core_side) / 2
    return core_side
    pass


def handleImage(sourceImagePath,targetImagePath):
    """
    去除图片黑边的原始方法
    :param sourceImagePath: 原始图片路径
    :param targetImagePath: 存储图片路径
    :return:
    """
    img = Image.open(sourceImagePath)
    if img.mode != "RGB":
        img = img.convert("RGB")
    width, height = img.size

    left = boundaryFinder(img, 0, width / 2, vCheck)
    right = boundaryFinder(img, width - 1, width / 2, vCheck)
    top = boundaryFinder(img, 0, height / 2, hCheck)
    bottom = boundaryFinder(img, height - 1, width / 2, hCheck)

    rect = (left, top, right, bottom)
    print(rect)
    region = img.crop(rect)
    region.save(targetImagePath)
    pass


def folderCheck(foldername):
    if foldername:
        if not os.path.exists(foldername):
            os.mkdir(foldername)
            print("Info: Folder \"%s\" created" % foldername)
        elif not os.path.isdir(foldername):
            print("Error: Folder \"%s\" conflict" % foldername)
            return False
    return True
    pass


# 递归创建文件
def check_and_create_dir(file_url):
    """
    判断文件是否存在，文件路径不存在则创建文件夹,和文件
    :param file_url: 文件路径，包含文件名
    :return:
    """
    if os.path.exists(file_url):
        return
    index = file_url.rfind("/")
    path = file_url[0:index]
    file = file_url[index + 1:len(file_url)]

    if not os.path.exists(path):
        os.makedirs(path)

    if "." in file:
        open(file_url, "w").close()  # 是文件创建文件
    else:
        os.mkdir(file_url)  # 是文件夹创建文件夹

def getDirFromDir(path):
    """
    获取该目录下的所有子目录
    :param path:
    :return:
    """
    L = []
    for dirpath, dirnames, filenames in os.walk(path):
        return dirnames

def getFileFromDir(path):
    """
    获取该目录下所有文件
    :param path:
    :return:
    """
    L = []
    for dirpath, dirnames, filenames in os.walk(path):
        for item in filenames:
            if item[0] == ".":
                continue
            L.append(item)
        return L

def getFilePathFromDir(path,suffixes):
    """
    获取该目录下的所有文件完整路径，不递归
    :param path:
    :return:
    """
    L = []
    for dirpath, dirnames, filenames in os.walk(path):
        for item in filenames:
            if item[0] == ".":
                continue
            if os.path.splitext(item)[1] in suffixes:
                L.append(os.path.join(dirpath, item))
        return L

def getFileNameFromPath(path):
    """
    从路径中获取文件名，不带后缀
    :param path:
    :return:
    """
    base = os.path.basename(path)
    return os.path.splitext(base)[0]

def removeAllFileFromDir(file_dir,suffixes):
    """
    删除该目录下指定后缀的文件
    :param path:
    :param suffixes:
    :return:
    """
    for dirpath, dirnames, filenames in os.walk(file_dir):
        for file in filenames:
            if file[0] == ".":
                continue
            if os.path.splitext(file)[1] in suffixes:
                currentPath = os.path.join(dirpath, file)
                os.remove(currentPath)



if __name__ == '__main__':
    from_dir = getFilePathFromDir("/Users/shu/Downloads/yangshu/ebike",[".jpg",".png"])
    print(from_dir)
    pass



